package org.onvivals.app.modules.auth.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.app.modules.auth.param.LoginParam;
import org.onvivals.app.modules.auth.service.AuthService;
import org.onvivals.app.modules.auth.util.SaTokenUtil;
import org.onvivals.common.web.Result;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 认证模块
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "小程序:认证")
@RequestMapping("/auth")
public class AuthController {

	private final AuthService authService;

	private final IUmsUserService umsUserService;

	/**
	 * 小程序登陆接口
	 */
	@PostMapping("/login")
	@Operation(summary = "小程序登陆")
	public Result<?> login(@Validated @RequestBody LoginParam loginParam) {
		Result<JSONObject> result = new Result<>();
		UmsUser member = authService.wxappLogin(loginParam);
		StpUtil.login(member.getUid());
		SaTokenUtil.setUser(member);
		SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
		JSONObject obj = new JSONObject();
		obj.put("tokenInfo", saTokenInfo);
		obj.put("userInfo", member);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}

//	/**
//	 * 注册接口
//	 */
//	@PostMapping("/register")
//	@Operation(summary = "注册")
//	public Result<?> register(@Validated @RequestBody LoginParam loginParam) {
//		Result<JSONObject> result = new Result<>();
//		UmsUser member = authService.register(loginParam);
//		StpUtil.login(member.getUid());
//		SaTokenUtil.setUser(member);
//		SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
//		JSONObject obj = new JSONObject();
//		obj.put("tokenInfo", saTokenInfo);
//		obj.put("userInfo", member);
//		result.setResult(obj);
//		result.success("注册成功");
//		return result;
//	}

	/**
	 * 获取当前登录人的信息
	 */
	@RequestMapping(value = "/getCurrentUserInfo", method = RequestMethod.GET)
	@Operation(summary = "获取当前登录人的信息")
	public Result<?> getCurrentUserInfo() {
		Result<UmsUser> result = new Result<>();
		Long userId = SaTokenUtil.getUserId();
		UmsUser umsUser = umsUserService.getById(userId);
		result.setResult(umsUser);
		result.success("获取成功");
		return result;
	}

	/**
	 * 退出登录
	 */
	@GetMapping("/logout")
	@Operation(summary = "退出登录")
	public Result<?> logout() {
		Long userId = SaTokenUtil.getUserId();
		log.info("用户退出登录，userId={}", userId);
		StpUtil.logout(userId);
		return Result.OK("退出成功", userId);
	}

}
